package socket;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private ExecutorService pool;
    private ServerSocket serverSocket;
private Set<Socket>clientSock= Collections.synchronizedSet(new HashSet<>());
    public Server(){
        try {
            System.out.println("正在启动服务器");
            serverSocket=new ServerSocket(8088);
            pool= Executors.newFixedThreadPool(20);
            System.out.println("服务端启动成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端链接...");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端链接了!");
                ClientHandler handler = new ClientHandler(socket);
               // Thread t = new Thread(handler);
               // t.start();
pool.execute(handler);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
    private class ClientHandler implements Runnable{
        private Socket socket;
        public ClientHandler(Socket socket){
            this.socket=socket;
        }

        @Override
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                int len;
                while ((len = in.read()) != -1) {

                    byte[] data = new byte[len];
                    in.read(data);
                    String message = new String(data, StandardCharsets.UTF_8);
                    System.out.println("客户端说:" + message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
